<template>
  <section class="component letter-template-config">
    <el-form :model="model" :rules="rules" ref="form" inline label-width="120px" class="text-left">
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="设为默认模板:" prop="isDefault">
            <el-checkbox v-model="model.isDefault" true-label="YES"	false-label="NO"></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-form-item label="模板编号:" prop="templateCode">
        <el-input v-model="model.templateCode" clearable :disabled="data?true:false"></el-input>
      </el-form-item>
      <el-form-item label="适用部门" prop="distributeType">
        <el-select v-model="model.distributeType">
          <el-option v-for="{code,name,index} in $dict.getDictData('DistributeType')" :key="index" :label="name" :value="code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板名称:" prop="templateName">
        <el-input v-model="model.templateName" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="templateStatus">
        <el-select v-model="model.templateStatus">
          <el-option v-for="{code,name,index} in $dict.getDictData('CommonState')" :key="index" :label="name" :value="code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-col :span="24">
        <el-form-item label="配置参数">
          <el-select v-model="selectedKey">
            <el-option v-for="{name,value} in keyResource" :key="value" :value="name" :label="name">
            </el-option>
          </el-select>
          <el-button @click="insertToTextArea" style="margin-left: 20px;">插入</el-button>
          <small style="color: #ff3122; margin-left: 5px;">选择的参数将插入到下方的文本编辑区域中</small>
        </el-form-item>
      </el-col>
      <el-col :span="24" id="editor-row">
        <div id="editor-container">
          <quill-editor ref="editor" v-model="content" :options="editorOption">
          </quill-editor>
        </div>
      </el-col>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="close">取消</el-button>
      <el-button @click="commit">确定</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { TemplateService } from "~/services/domain-service/template.service";
import { State, Action, Getter } from "vuex-class";
import { Emit, Prop } from "vue-property-decorator";
import { Form } from "element-ui";
import { CommonService } from "~/utils/common.service";
import { quillEditor } from 'vue-quill-editor';
import { KeyResource, EditorOption } from './letter-template.config'


@Component({
  components: {
    quillEditor
  }
})
export default class LetterTemplateConfig extends Vue {

  @Dependencies(TemplateService)
  private templateService: TemplateService;

  @Prop()
  private data: any

  private selectedKey: any = ''
  private keyResource: any[] = KeyResource
  private editorOption: any = EditorOption
  private content: any = ''

  private model: any = {
    templateCode: "", // 模版编号
    templateName: "", // 模版名称
    templateStatus: "ENABLED", // 模版状态
    templateContent: "", // 模版内容
    templateCategory: "CONTRACT",
    distributeType: "",
  }

  private rules: any = {
    templateCode: { required: true, message: "请输入模板编号" },
    templateName: { required: true, message: "请输入模板名称" },
    templateStatus: { required: true, message: '请选择模板状态' },
    distributeType: { required: true, message: '请选择适用部门' },
    templateContent: { required: true, message: '请输入合同模板内容' }
  }



  public refresh() {
    if (!this.data) {
      const templateForm = this.$refs["form"] as Form
      templateForm.resetFields()
      this.content = ''
      this.selectedKey = ''
    } else {
      this.selectedKey = ''
      this.formatContent(1)
      this.model.templateCode = this.data.templateCode
      this.model.templateName = this.data.templateName
      this.model.templateStatus = this.data.templateStatus
      this.model.isDefault = this.data.isDefault
      this.model.distributeType = this.data.distributeType
    }
  }

  @Emit('refreshData')
  private refreshData() { }
  @Emit('close')
  private close() { }

  /**
   * 提交新建模板按钮
   */
  private commit(type) {
    const templateForm = this.$refs["form"] as Form;
    templateForm.validate(validate => {
      if (!validate) return;
      if (!this.formatContent(0)) return
      const params: any = { ...this.model }
      if (this.data) {
        params.id = this.data.id
      }
      this.templateService.createTemplate(params).subscribe(
        () => {
          this.refreshData()
          this.close()
          this.$message.success('操作成功')
        }
      )
    });
  }

  /**
   * 插入选中的参数到富文本光标所在之处
   */
  private insertToTextArea() {
    if (this.selectedKey === '') {
      return
    }
    const editor: any = this.$refs['editor'];
    const quill = editor.quill;
    quill.focus()
    const selection = quill.getSelection()
    const insertKey = '[' + this.selectedKey + ']'
    if (selection.length > 0) {
      // 如果是选中模式需要先删除原有数据
      quill.deleteText(selection.index, selection.length)
    }
    quill.insertText(selection.index, insertKey)
    quill.setSelection(selection.index + insertKey.length, 0)
  }

  private formatContent(mode): boolean {
    let message = ''
    let regex: any = ''
    if (mode === 0) {
      if (!this.content) {
        this.$message.error('请编辑模板内容')
        return false
      }
      message = this.content
      this.keyResource.map((obj) => {
        // 0 替换为Value
        regex = new RegExp('\\[\\' + obj.name + '?\\]', 'g')
        message = message.replace(regex, obj.value)
      })
      // 先替换\t
      regex = new RegExp('\\t{1}', 'g')
      message = message.replace(regex, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
      // 然后替换\s [空格]
      regex = new RegExp('\\s{2}?', 'g')
      message = message.replace(regex, '&nbsp;&nbsp;')
      this.model.templateContent = message
    } else {
      if (this.data.templateContent) {
        message = this.data.templateContent
        // 1 替换为name
        this.keyResource.map((obj) => {
          regex = new RegExp('\\' + obj.value + '?', 'g')
          message = message.replace(regex, '[' + obj.name + ']')
        })
        this.content = message
      } else {
        this.model.templateContent = ''
        this.content = ''
      }
    }
    return true
  }

}
</script>
<style lang="less">
@import "quill/dist/quill.core.css";
@import "quill/dist/quill.snow.css";
@import "quill/dist/quill.bubble.css";

#editor-row {
  height: 320px;
}
#editor-container {
  margin-left: 30px;
}
.quill-editor {
  height: 250px;
}
</style>
